﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using HZU.ZP.Domain.IService;
using HZU.ZP.Domain.IService.Resume;
using HZU.ZP.Domain.Model;
using HZU.ZP.Domain.Model.Resume;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HZU.ZP.Controllers
{
    public class ApplyRecordController : Controller
    {
        private IApplicantService _applicantService;
        private IInformationService _informationService;
        private IPositionService _positionService;
        private IApplyRecordService _applyRecordService;
        private ICompanyService _companyService;
        private IAwardService _awardService;
        private IEducationExperienceService _educationExperienceService;
        private IJobIntentionService _jobIntentionService;
        private IMasterSkillService _masterSkillService;
        private IProjectExperienceService _projectExperienceService;
        private ISelfEvaluationService _selfEvaluationService;
        public ApplyRecordController(IApplicantService applicantService, IInformationService informationService,
            IPositionService positionService, IApplyRecordService applyRecordService, ICompanyService companyService,
            IAwardService awardService, IEducationExperienceService educationExperienceService, 
            IJobIntentionService jobIntentionService,IMasterSkillService masterSkillService,
            IProjectExperienceService projectExperienceService,ISelfEvaluationService selfEvaluationService)
        {
            _applicantService = applicantService;
            _informationService = informationService;
            _positionService = positionService;
            _applyRecordService = applyRecordService;
            _companyService = companyService;
            _awardService = awardService;
            _educationExperienceService = educationExperienceService;
            _jobIntentionService = jobIntentionService;
            _masterSkillService = masterSkillService;
            _projectExperienceService = projectExperienceService;
            _selfEvaluationService = selfEvaluationService;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Applicant")]
        [HttpPost]
        public IActionResult Add(string email, int PositionId)
        {
            if (User.Identity.Name != email)
            {
                return NotFound();
            }            
            Applicant applicant = new Applicant();
            Information information = new Information();
            Position position = new Position();
            ApplyRecord applyRecord = new ApplyRecord();
            applicant = _applicantService.GetApplicant(email);
            if (applicant == null)
                return Json(AjaxResult.ReturnMessage(4040, "不存在该学生"));
            information = _informationService.GetInformation(applicant.Id.Value);
            if (information == null)
                return Json(AjaxResult.ReturnMessage(4050, "该学生未存在简历，请创建！"));
            position = _positionService.GetById(PositionId);
            if (position == null || position.Status != 1)
                return Json(AjaxResult.ReturnMessage(4060, "该职位已暂停或不存在！"));
            if (_applyRecordService.GetByAppIdAndId(applicant.Id.Value, position.Id.Value) != null)
                return Json(AjaxResult.ReturnMessage(4070, "已申请该职位"));
            applyRecord.Processing = 1;
            applyRecord.ApplicantId = information.ApplicantId.Value;
            applyRecord.ApplicantName = information.Name;
            applyRecord.ApplicantEmail = information.Email;
            applyRecord.ApplicantSex = information.Sex;
            applyRecord.PositionName = position.Name;
            applyRecord.PositionId = position.Id.Value;
            applyRecord.CompanyName = position.CompanyName;
            applyRecord.CompanyId = position.CompanyId;
            applyRecord.CreateTime = DateTime.Now;
            _applyRecordService.Add(applyRecord);
            return Json(AjaxResult.ReturnMessage(001, "申请成功！"));
        }

        [Authorize]
        [HttpPost]
        public IActionResult Update(int applyRecordId, int processing)
        {
            ApplyRecord applyRecord = new ApplyRecord();            
            applyRecord = _applyRecordService.GetById(applyRecordId);
            if (applyRecord == null)
            {
                return Json(AjaxResult.ReturnMessage(999, "该职位不存在！"));
            }
            if (!(applyRecord.Processing == 2 || applyRecord.Processing == 3))
            {
                return Json(AjaxResult.ReturnMessage(4040, "该学生已被处理！"));
            }
            applyRecord.Processing = processing;
            _applyRecordService.Update(applyRecord);
            return Json(new { returnCode = "001" });
        }
        [Authorize(Roles = "Applicant")]
        [HttpGet]
        public IActionResult GetApplyRecordApp(string email, int processing = 1, int pageIndex = 1)
        {
            if (User.Identity.Name != email)
            {
                return NotFound();
            }
            int pageSize = 20;
            IList<ApplyRecord> applyRecordView = new List<ApplyRecord>();
            Applicant applicant = new Applicant();           
            applicant = _applicantService.GetApplicant(email);
            applyRecordView = _applyRecordService.GetByApplicant(applicant.Id.Value, processing, pageIndex);
            ViewData["Total"] = (int)Math.Ceiling((double)_applyRecordService.GetAppCount(applicant.Id.Value, processing) / pageSize);
            ViewData["Processing"] = processing;
            ViewData["PageIndex"] = pageIndex;
            if ((int)ViewData["Total"] == 0)
                ViewData["PageIndex"] = 0;

            ViewData["Title"] = "申请记录";
            return View(applyRecordView);
        }
        [Authorize(Roles = "Company")]
        [HttpGet]
        public IActionResult GetApplyRecordCom(string email, int processing = 1, int pageIndex = 1)
        {
            if (User.Identity.Name != email)
            {
                return NotFound();
            }
            int pageSize = 20;
            IList<ApplyRecord> applyRecordView = new List<ApplyRecord>();
            Company company = new Company();
            company = _companyService.GetByEmail(email);
            applyRecordView = _applyRecordService.GetByCompany(company.Id.Value, processing, pageIndex);
            ViewData["Total"] = (int)Math.Ceiling((double)_applyRecordService.GetComCount(company.Id.Value, processing) / pageSize);
            ViewData["Processing"] = processing;
            ViewData["PageIndex"] = pageIndex;
            if ((int)ViewData["Total"] == 0)
                ViewData["PageIndex"] = 0;

            ViewData["Title"] = "学生申请记录";
            return View(applyRecordView);
        }
        [Authorize(Roles = "Company")]
        [HttpGet]
        public IActionResult HandleRecord(string email, int id)
        {
            if (User.Identity.Name != email)
            {
                return NotFound();
            }
            HandleResumeView resumeView = new HandleResumeView();
            Company company = new Company();
            ApplyRecord applyRecord = new ApplyRecord();            
            company = _companyService.GetByEmail(email);
            applyRecord = _applyRecordService.GetByComAndId(company.Id.Value, id);
            resumeView.Processing = applyRecord.Processing;
            resumeView.ApplyRecordId = applyRecord.Id.Value;
            if (applyRecord.Processing == 1)
            {
                applyRecord.Processing = 2;
                _applyRecordService.Update(applyRecord);
            }

            ResumeInfo resume = new ResumeInfo();           

            int applicantId = applyRecord.ApplicantId;

            resume.Information = _informationService.GetInformation(applicantId);
            resume.SelfEvaluation = _selfEvaluationService.GetSelfEvaluation(applicantId);
            resume.JobIntention = _jobIntentionService.GetJobIntention(applicantId);
            resume.MasterSkills = _masterSkillService.GetMasterSkillList(applicantId);
            resume.Awards = _awardService.GetAwardList(applicantId);
            resume.ProjectExperiences = _projectExperienceService.GetProjectExperienceList(applicantId);
            resume.EducationExperiences = _educationExperienceService.GetEducationExperienceList(applicantId);

            resumeView.Resume = resume;

            ViewData["Title"] = "简历处理";


            return View(resumeView);
        }

        [Authorize(Roles = "Company")]
        [HttpPost]
        public IActionResult SendEmail([FromBody]EmailModel emailModel)
        {
            SmtpClient client = new SmtpClient()
            {
                Host = "smtp.exmail.qq.com", //"smtp.qq.com";企业账号用smtp.exmail.qq.com
                Port = 25,
                //通过网络发送到SMTP服务器
                DeliveryMethod = SmtpDeliveryMethod.Network,
                //发件人登录邮箱的用户名和密码
                //Credentials = new NetworkCredential(model.UserId, model.Password.Trim())
                //  Credentials = new NetworkCredential("2369196274@qq.com", "oawlukavboveeagf")
                Credentials = new NetworkCredential(emailModel.CompanyEmail, emailModel.Password)
            };
            MailAddress fromAddress = new MailAddress(emailModel.CompanyEmail, emailModel.CompanyName);
            MailAddress toAddress = new MailAddress(emailModel.ApplicantEmail);
            //MailAddress fromAddress = new MailAddress("2369196274@qq.com", "xx企业");
            //MailAddress toAddress = new MailAddress("2444794619@qq.com", "xx人");
            MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
            mailMessage.IsBodyHtml = true;
            mailMessage.Subject = $"面试邀请：{emailModel.PositionName}(收到请回复，谢谢)";
            mailMessage.Body = $"<h2 style=\" color: blue; text - align:center\">惠州学院招聘网</h2><p>{emailModel.ApplicantName},您好~</p><p>您的简历已经通过我们的筛选，很高兴通知您参加我们的面试。</p>" +
                $"<h5>面试公司：<a href=\"#\">{emailModel.CompanyName}</a></h5><h5>面试职位：<a href=\"#\">{emailModel.PositionName}</a></h5><h5>面试时间：<a href=\"#\">{emailModel.StartTime}</a></h5>" +
                $"<h5>面试地点：<a href=\"#\">{emailModel.Address}</a></h5><h5>联系人：<a href=\"#\">{emailModel.Contacts}</a></h5><h5>联系电话：<a href=\"#\">{emailModel.PositionName}</a></h5>" +
                $"<h5>备注：<a href=\"#\">{emailModel.Remarks}</a></h5><h5>小建议:</h5><ol><li>如遇特殊情况不能准时参加请提前告知企业；</li><li>建议携带一份简历和相关材料；</li><li>提前<a>10-20</a>分钟到达面试地点；</li><li>着装干净简洁，不要太过随意。</li></ol>";
            mailMessage.SubjectEncoding = Encoding.UTF8;
            mailMessage.BodyEncoding = Encoding.UTF8;// Encoding.GetEncoding("GB2312");
            mailMessage.Priority = MailPriority.High;
            try
            {
                client.Send(mailMessage);//发送邮件
                                         // result.Message = "发送成功！";
                                         // result.IsSuccess = true;
                return Json(new { returnCode = "001" });
            }
            catch (Exception ex)
            {
                //  1. 连接SMTP服务器失败
                //  2. 用户名或密码验证错误
                //  3. 超时
                //  这三种情况导致抛出SmtpClient异常
                // -------
                //result.Message = "测试失败！";
                //result.IsSuccess = false;
                return Json(new { returnCode = "999" });
            }

            //return result;
        }
        [Authorize(Roles = "Company")]
        [HttpGet]
        public IActionResult SendEmail(string companyEmail, int applyRecordId)
        {
            if (User.Identity.Name != companyEmail)
            {
                return NotFound();
            }
            
            ApplyRecord applyRecord = new ApplyRecord();
            Company company = new Company();
  
            company = _companyService.GetByEmail(companyEmail);
            applyRecord = _applyRecordService.GetByComAndId(company.Id.Value, applyRecordId);
            if (applyRecord == null)
            {
                return NotFound();
            }
            ViewData["companyEmail"] = companyEmail;
            ViewData["companyName"] = applyRecord.CompanyName;
            ViewData["positionName"] = applyRecord.PositionName;
            ViewData["applicantEmail"] = applyRecord.ApplicantEmail;
            ViewData["applicantName"] = applyRecord.ApplicantName;

            ViewData["Title"] = "发送面试邮件";
            return View();
        }
    }
}
